package com.example.module_hp_zao_yin_media.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.example.module_hp_zao_yin_media.R;
import com.example.module_hp_zao_yin_media.activity.HpZaoYinPhotoInfoActivity;
import com.example.module_hp_zao_yin_media.base.BaseMvvmActivity;
import com.example.module_hp_zao_yin_media.base.BaseViewModel;
import com.example.module_hp_zao_yin_media.databinding.ActivityHpZaoYinPhotoBinding;
import com.example.module_hp_zao_yin_media.util.AudioRecordDemo;
import com.example.module_hp_zao_yin_media.util.AudioRecordDemo2;
import com.example.module_hp_zao_yin_media.util.Utils;
import com.fwlst.lib_base.fragment.BaseMvvmFragment;
import com.fwlst.lib_base.utils.BaseUtils;
import com.fwlst.lib_base.utils.JtXXPermissions;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.PictureResult;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import kotlin.Unit;
import kotlin.jvm.functions.Function0;


public class HpZaoYinPhotoFragment extends BaseMvvmFragment<ActivityHpZaoYinPhotoBinding, BaseViewModel> {
    private AudioRecordDemo2 audioRecordDemo;
    private List<Double> numArr = new ArrayList<>();
    private Handler mHandler;

    @Override
    protected int initLayout() {
        return R.layout.activity_hp_zao_yin_photo;
    }

    @Override
    protected int initBR() {
        return 0;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle bundle) {
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            binding.tvQuanXian.setVisibility(View.GONE);
            binding.camera.setLifecycleOwner(this);
            //设置相机拍照事件
            binding.camera.addCameraListener(new CameraListener() {
                @Override
                public void onPictureTaken(@NonNull PictureResult result) {
                    super.onPictureTaken(result);
                    if (binding.camera.isTakingVideo()) {
                        return;
                    }
                    result.toBitmap(new BitmapCallback() {
                        @Override
                        public void onBitmapReady(@Nullable Bitmap bitmap) {
                            Utils.PHOTO_BM = bitmap;
                            navigateTo(HpZaoYinPhotoInfoActivity.class);
                        }
                    });
                }
            });

            //获取录音机权限
            audioRecordDemo = new AudioRecordDemo2(this);

            mHandler = new Handler(Looper.getMainLooper());
            startRepeatedTask();
        } else {
            binding.tvQuanXian.setVisibility(View.VISIBLE);
        }

        binding.tvQuanXian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPermission();
            }
        });


        //点击事件-返回
        binding.hpZaoYinPhotoBt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        //点击事件-拍照
        binding.hpZaoYinPhotoBt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (binding.camera.isTakingPicture()) return;
                binding.camera.takePictureSnapshot();
            }
        });
        //点击事件-切换摄像头
        binding.hpZaoYinPhotoBt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (binding.camera.isTakingPicture() || binding.camera.isTakingVideo()) {
                    return;
                }
                binding.camera.toggleFacing();
            }
        });

    }

    //开启录音权限
    private void getPermission() {
        List<String> pre = new ArrayList<>();
        pre.add(Manifest.permission.RECORD_AUDIO);
        pre.add(Manifest.permission.CAMERA);
        JtXXPermissions.INSTANCE.requestPermission(requireContext(), "", pre, new Function0<Unit>() {
            @Override
            public Unit invoke() {
                binding.tvQuanXian.setVisibility(View.GONE);

                binding.camera.setLifecycleOwner(requireActivity());
                //设置相机拍照事件
                binding.camera.addCameraListener(new CameraListener() {
                    @Override
                    public void onPictureTaken(@NonNull PictureResult result) {
                        super.onPictureTaken(result);
                        if (binding.camera.isTakingVideo()) {
                            return;
                        }
                        result.toBitmap(new BitmapCallback() {
                            @Override
                            public void onBitmapReady(@Nullable Bitmap bitmap) {
                                Utils.PHOTO_BM = bitmap;
                                navigateTo(HpZaoYinPhotoInfoActivity.class);
                            }
                        });
                    }
                });

                //获取录音机权限
                audioRecordDemo = new AudioRecordDemo2(HpZaoYinPhotoFragment.this);

                mHandler = new Handler(Looper.getMainLooper());
                startRepeatedTask();

                audioRecordDemo.getNoiseLevel(new AudioRecordDemo2.MonitorInterface() {
                    @Override
                    public void monitorListener(Double res) {
                        binding.hpZaoYinTv0.setText(res + "dB");
                        if (res > 0) {
                            numArr.add(res);
                            setNumArr();
                        }
                    }
                });
                return null;
            }
        });
    }

    //计算list最大，最小，平均值
    private void setNumArr() {
        Double maxNum = Collections.max(numArr);
        Double minNum = Collections.min(numArr);
        Double sum = 0.0;
        for (Double i : numArr) {
            sum += i;
        }
        Double avNum = sum / numArr.size();
        avNum = Math.round(avNum * 10) / 10.0;
        binding.hpZaoYinTv1.setText(maxNum + "dB");
        binding.hpZaoYinTv2.setText(avNum + "dB");
        binding.hpZaoYinTv3.setText(minNum + "dB");

    }

    private void startRepeatedTask() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                // 执行任务逻辑
                setTime();
                // 继续下一次定时任务
                startRepeatedTask();
            }
        }, 1000); // 1秒后执行
    }

    //设置时间方法
    private void setTime() {
        long m = System.currentTimeMillis() / 1000;
        binding.hpZaoYinPhotoTv1.setText(BaseUtils.INSTANCE.formatTime((int) m, "yyyy.MM.dd"));
        binding.hpZaoYinPhotoTv2.setText(BaseUtils.INSTANCE.formatTime((int) m, "HH:mm"));
        binding.hpZaoYinPhotoLl.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding.camera.destroy();
        if (audioRecordDemo != null) {
            audioRecordDemo.stop();
        }
        if (mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (audioRecordDemo != null) {
            audioRecordDemo.stop();
        }
    }
}